package com.lanp.gencode.utils;

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.RootDoc;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javadoc.FieldDocImpl;
import com.sun.tools.javadoc.Main;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class DocUtil {

    /**
     * 会自动注入
     */
    private static RootDoc rootDoc;

    /**
     * 会自动调用这个方法
     *
     * @param root root
     * @return true
     */
    public static boolean start(RootDoc root) {
        rootDoc = root;
        return true;
    }

    public static List<VoDoc> JavaToDoc(String javaFilePath) {
        Main.execute(new String[]{"-doclet", DocUtil.class.getName(), "-docletpath",
                DocUtil.class.getResource("/").getPath(), "-encoding", "utf-8", javaFilePath});

        ClassDoc[] classes = rootDoc.classes();

        if (classes == null || classes.length == 0) {
            return null;
        }
        ClassDoc classDoc = classes[0];
        // 获取属性名称和注释
        FieldDoc[] fields = classDoc.fields(false);

        List<VoDoc> VoDocs = new ArrayList<>();
        for (FieldDoc field : fields) {
            //JCTree.JCTypeApply vartypeAA = (JCTree.JCTypeApply) ((JCTree.JCVariableDecl) ((FieldDocImpl) field).findTree()).vartype;
            String name = "";
            JCTree.JCVariableDecl decl = ((JCTree.JCVariableDecl) ((FieldDocImpl) field).findTree());
            if( decl.vartype instanceof JCTree.JCTypeApply){
                JCTree.JCTypeApply apply = (JCTree.JCTypeApply) decl.vartype;
                Name listName = ((JCTree.JCIdent) apply.clazz).name;
                if (StringUtils.equals(listName.toString(),"List")) {
                    Name nameVal = ((JCTree.JCIdent) apply.arguments.get(0)).name;
                    name = nameVal.toString();
                }
            }

            VoDocs.add(new VoDoc(field.name(), field.type().typeName(), field.commentText(), name.toString()));
        }
        return VoDocs;

    }

    /**
     * 对象文档注释文档信息
     */
    @Data
    public static class VoDoc {
        private String fieldName;
        private String fieldType;
        private String commentText;
        private String Tclass;//泛型的类

        public VoDoc(String fieldName, String fieldType, String commentText, String tclass) {
            this.fieldName = fieldName;
            this.fieldType = fieldType;
            this.commentText = commentText;
            this.Tclass = tclass;
        }
    }

}
